from hashlib import md5
from pprint import pprint

from flask import request

from config import MD5_SALT
from db_init import db
from swaager_init import siwa
from model.model import User, Good, Code
from tools.tools import item2dict, my_route, my_cache
from flask_login import login_required, current_user, logout_user, login_user
from sqlalchemy import text

bxx = siwa.blueprint('bxx', __name__)


@bxx.route('/login', methods=['POST'])
def login():
    phone = request.form.get('phone')
    pwd = request.form.get('pwd')
    user = User.query.filter_by(phone=phone).first()
    if user and user.pwd == md5(pwd.encode() + MD5_SALT).hexdigest():
        login_user(user)
        return my_route(200, item2dict(user))

    return my_route(206)


@bxx.route('/logout', methods=['GET'])
@login_required
def logout():
    logout_user()
    return my_route(200)


@bxx.route('/goods', methods=['GET'])
@login_required
def goods():
    order = request.args.get('order', 'id')
    open = int(request.args.get('open'))
    goods = Good.query.filter_by(open=open).order_by(text(order)).all()

    # 未开奖的商品列表页
    if not open:
        return my_route(200, item2dict(goods))

    codes = Code.query.filter(Code.open == True, Code.good_id.in_([good.id for good in goods])).all()

    ret_codes = item2dict(codes)
    for dict_data, orm_data in zip(ret_codes, codes):
        dict_data['good'] = item2dict(orm_data.good)
        dict_data['user'] = item2dict(orm_data.user)
    return my_route(200, ret_codes)






@bxx.route('/code', methods=['POST'])
@login_required
def buy_code():
    num = int(request.form.get('num'))
    g_id = int(request.form.get('g_id'))
    codes = Code.query.filter_by(open=False, good_id=g_id).limit(num).all()
    for i in codes:
        i.user_id = current_user.id
    db.session.commit()
    return my_route(200)


@bxx.route('/code', methods=['get'])
@login_required
def get_my_codes():
    goods = Code.query.filter_by(user_id=current_user.id).all()
    ret_codes = item2dict(goods)
    for dict_data, orm_data in zip(ret_codes, goods):
        dict_data['god_name'] = orm_data.good.code_id[0].good.name

    return my_route(200, ret_codes)

# [({'code': '1233', 'good_id': 1, 'id': 1, 'open': False, 'user_id': 14},< Code 1 >),
#  ({'code': '123123', 'good_id': 1, 'id': 2, 'open': False, 'user_id': 14},< Code 2 >),
#  ({'code': '5342345', 'good_id': 1, 'id': 4, 'open': False, 'user_id': 14},< Code 4 >)]
